{extend name="public:base"}
{block name='css'}
<link href="__PUBLIC__/css/plugins/iCheck/custom.css" rel="stylesheet">
{/block}
{block name='body'}
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">

    <form method="post" class="form-horizontal" id="commentForm" onsubmit="myAjaxSubmit();return false;" action="" >
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>{empty name='data'}添加{else/}编辑{/empty}商品</h5>
                    <input type="submit" class="btn btn-primary" style="margin-left: 50px;" value="保存"/>
                    <a href="{:url('index')}" class="btn btn-sm btn-primary pull-right m-t-n-xs">返回</a>
                </div>
                <div class="ibox-content">
                    <input type="hidden" name="id" value="{$data.id|default=''}">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">商品类别</label>
                        <div class="col-sm-8">
                            <select class="input-sm form-control" name="cate_id">
                                <option value="">请选择商品分类</option>
                                {foreach name="clist" item="li"}
                                <option value="{$li.id}" {if condition="$data.cate_id eq $li.id"}selected{/if}>{$li.title}</option>
                                {notempty name="li.list"}
                                {foreach name="li.list" item="son"}
                                <option value="{$son.id}" {if condition="isset($data.cate_id) && $data.cate_id eq $son.id"}selected{/if}>|-{$son.title}</option>
                                {/foreach}
                                {/notempty}
                                {/foreach}
                            </select>
                        </div>
                    </div>
                    <!-- {if $data.cate_id1!==3}
                    <div class="form-group">
                        <label class="col-sm-2 control-label">所属等级</label>
                        <div class="col-sm-8">
                            <select class="input-sm form-control" name="level_id">
                                {foreach name="level" item="li"}
                                <option value="{$li.id}" {if condition="$data.level_id eq $li.id"}selected{/if}>{$li.title}</option>
                                {/foreach}
                                
                            </select>
                        </div>
                    </div>
                    {/if} -->
                    <div class="form-group">
                        <label class="col-sm-2 control-label">商品名称</label>
                        <div class="col-sm-8">
                            <input type="text" name="title" value="{$data.title|default=''}" placeholder="请输入商品名称" class="input-sm form-control">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">商品图片</label>
                        <div class="col-sm-10">

                            <div class="col-sm-12"  style="padding-left:0px;">
                                <div class="img_info">
                                    <img src="{$data.img|default='__PUBLIC__/img/goods.jpg'}" id="up_1" width="100"/>
                                    <input type="hidden" name="img" class="i" value="{$data.img|default=''}" />
                                    <input class="i" id="inp_1" type="file" accept="image/gif,image/jpeg,image/jpg,image/png"/>
                                </div>
                            </div>

                            <div class="col-sm-12"  style="padding-left:0px;">
                                <span class="help-block m-b-none">图片大小：200px*200px以上1:1比例图片</span>
                            </div>
                        </div>
                    </div>


                    <div class="form-group">
                        <label class="col-sm-2 control-label">详情图片</label>
                        <div class="col-sm-10">
                            <div class="col-sm-12" style="padding-left:0px;">
                                <button type="button" class="btn btn-primary" onclick="addImg();">添加图片</button>
                            </div>

                            <div class="col-sm-12 imgKj"  style="padding-left:0px;">
                                {notempty name='data.imgs'}
                                {foreach name="data.imgs" item="li" key="k"}
                                <div class="img_info">
                                    <img src="{$li}" id="up_{$k+1}" width="100"/>
                                    <input type="hidden" name="imgs[]" class="i" value="{$li}" />
                                    <span onclick="delImgKj(this);">删除</span>
                                </div>
                                {/foreach}
                                {/notempty}
                            </div>


                            <div class="col-sm-12"  style="padding-left:0px;">
                                <span class="help-block m-b-none">图片大小：300px*200px以上3:2比例图片</span>
                            </div>
                        </div>
                    </div>
                    <style type="text/css">
                        .img_info{width:104px;height:auto;overflow:hidden;position:relative;margin:0px 10px 10px 0px;float:left;}
                        .img_info img{width:100px;height:100px;border:1px solid #ccc;padding:1px;}
                        .img_info input.i{width:100px;height:100px;left:0px;top:0px;opacity:0;position:absolute;z-index:1;cursor:pointer;padding:0px;margin:0px;}
                        .img_info p{width:100px;height:22px;}
                        .img_info p input{position:relative;width:100%;height:100%;border:1px solid #ccc;}
                        .img_info span{display:inline-block;width:100%;height:22px;line-height:22px;text-align:center;cursor:pointer;}
                    </style>
                    <script type="text/javascript">
                        function addImg(){
                            var length=$('.imgKj .img_info').length;
                            if(length >= 5){
                                alert('最多添加5张图片！');return false;
                            }
                            var time=new Date().getTime();
                            var input_id = 'in_'+time;
                            //<input type="text" name="sort'+time+'"value="'+length+'"/>
                            $('.imgKj').append('<div class="img_info"><img src="__PUBLIC__/img/goods.jpg"/><input name="imgs[]" type="hidden"/><input class="i" id="'+input_id+'" type="file" accept="image/gif,image/jpeg,image/jpg,image/png"/><span onclick="delImgKj(this);">删除</span></div>');
                            $('#'+input_id).change(function(event) {
                                var self = this;
                                var files = event.target.files || event.dataTransfer.files;
                                var formData = new FormData();
                                formData.append('imgFile', files[0]);
                                var ajax = new XMLHttpRequest();
                                ajax.open("POST", "{:url('index/Index/saveImg')}", true);
                                ajax.send(formData);
                                ajax.onreadystatechange = function() {
                                    if (ajax.readyState == 4) {
                                        if (ajax.status >= 200 && ajax.status < 300 || ajax.status == 304) {
                                            var data = JSON.parse(ajax.responseText);
                                            if (data.status == 'y') {
                                                $(self).prev().val(data.data.src);
                                                $(self).prev().prev().attr('src', data.data.src);
                                            } else {
                                                layer.msg(data.info);
                                            }
                                        }
                                    }
                                }
                            });
                        }

                        function delImgKj(obj){
                            $(obj).parents('.img_info').remove();
                        }



                    </script>

                    <!-- <div class="form-group">
                        <label class="col-sm-2 control-label">原价</label>
                        <div class="col-sm-8">
                            <input type="number" step="0.01" min="0.01" max="999999.99" name="price" value="{$data.price|default=''}" placeholder="请输入商品展示价格" class="input-sm form-control">
                        </div>
                    </div> -->
                    <div class="form-group">
                        <label class="col-sm-2 control-label">单价</label>
                        <div class="col-sm-8">
                            <input type="number" step="0.01" min="0.01" max="999999.99" name="unit_price" value="{$data.unit_price|default=''}" placeholder="请输入商品单价" class="input-sm form-control">
                        </div>
                    </div>

                    <div class="hr-line-dashed"></div>
                    <!-- <div class="form-group">
                        <label class="col-sm-2 control-label">商品规格</label>
                        <div class="col-sm-10">
                            <div class="col-sm-12" style="padding-left:0px;">
                                <button type="button" class="btn btn-primary" onclick="addSpec();">添加规格</button>
                            </div>
                            <div class="col-sm-12" style="padding-left:0px;">
                                <table class="table table-bordered specKj" style="width:auto;">
                                    <tbody>
                                    {notempty name="data.spec"}
                                    {foreach name="data.spec.spec" item="li" key="k"}
                                        <tr class="trspec{$k}">
                                            <td style="width:100px;">
                                                <b>{$li.title}：</b>
                                                <input type="hidden" name="spec[{$k}][title]" value="{$li.title}">
                                            </td>
                                            <td class="tdspec{$k}">
                                                {foreach name="li.value" item="val" key="ks"}
                                                    <span>{$val} <i class="fa fa-times-circle" onclick="delTdSpec(this,{$k});"></i><input type="hidden" name="spec[{$k}][value][]" value="{$val}">&nbsp;&nbsp;</span>
                                                {/foreach}
                                            </td>
                                            <td>
                                                <a href="javascript:void(0);" onclick="addTdSpec({$k});" class="btn btn-info btn-xs edit"><i class="fa fa-list"></i> 添加规格值</a>&nbsp;&nbsp;
                                                <a href="javascript:delSpec({$k});" class="btn btn-danger btn-xs delete"><i class="fa fa-trash-o"></i> 删除规格</a>
                                            </td>
                                        </tr>
                                    {/foreach}
                                    {/notempty}
                                    </tbody>
                                </table>
                            </div>
                            <div class="col-sm-12" style="padding-left:0px;">
                                <table class="table table-bordered specvalue table-hover" style="width:auto;">
                                    <thead>
                                    </thead>
                                    <tbody>
                                    </tbody>
                                    <tfoot>
                                    </tfoot>
                                </table>

                            </div>
                        </div>
                    </div> -->
                    <style type="text/css">
                        .table-bordered span{cursor:pointer;}
                        .table-bordered span:hover i{color:red;}
                    </style>

                    <script type="text/javascript">
                        var spec = new Array();
                        /*{notempty name="data.spec"}*/
                        /*{foreach name="data.spec.spec" item="li" key="k"}*/
                        spec[{$k-1}]=new Array();
                        spec[{$k-1}]['title']='{$li.title}';
                        spec[{$k-1}]['value']=new Array();
                        /*{foreach name="li.value" item="val" key="ks"}*/
                        spec[{$k-1}]['value'][{$ks}]='{$val}';
                        /*{/foreach}*/
                        /*{/foreach}*/
                        /*{/notempty}*/
                        //alert(spec);
                    </script>
                    <script type="text/javascript">


                        //去除左右空格
                        function trim(s){
                            return s.replace(/(^\s*)|(\s*$)/g, "");
                        }
                        //添加规格
                        function addSpec(){
                            var length=$('.specKj tr').length;
                            if(length >= 2){
                                layer.msg('最多添加2个规格！');
                                return false;
                            }
                            length++;

                            layer.prompt({
                                title: '请输入规格名称：',
                                formType: 0 ,
                            }, function(name,index){
                                var names=trim(name);
                                for(var i=0;i < spec.length;i++){
                                    if(spec[i]['title'] == names){
                                        layer.msg('已经存在“'+names+'”这个规格了！');
                                        return false;
                                    }
                                }

                                $('.specKj tbody').append('<tr class="trspec'+length+'"><td style="width:100px;"><b>'+names+'：</b><input type="hidden" name="spec['+length+'][title]" value="'+names+'" /></td><td class="tdspec'+length+'"></td><td><a href="javascript:void(0);" onclick="addTdSpec('+length+');" class="btn btn-info btn-xs edit" ><i class="fa fa-list"></i> 添加规格值</a>&nbsp;&nbsp;<a href="javascript:delSpec('+length+');" class="btn btn-danger btn-xs delete"><i class="fa fa-trash-o"></i> 删除规格</a></td></tr>');

                                layer.close(index);

                                //往数组里插入规格
                                spec[length-1]=new Array();
                                spec[length-1]['title']=names;
                                spec[length-1]['value']=new Array();
                                //执行循环数组
                                specFor();

                            });
                            return false;
                        }

                        //添加规格值
                        function addTdSpec(id){
                            var length=$('.tdspec'+id).find('span').length;
                            if(length >= 5){
                                layer.msg('最多添加5个规格值！');
                                return false;
                            }

                            layer.prompt({
                                title: '请输入规格值：',
                                formType: 0 ,
                            }, function(name,index){
                                var names=trim(name);

                                for(var i=0;i < spec[id-1]['value'].length;i++){
                                    if(spec[id-1]['value'][i] == names){
                                        layer.msg(spec[id-1]['title']+'下已经存在“'+names+'”这个规格值了！');
                                        return false;
                                    }
                                }

                                $('.tdspec'+id).append('<span>'+names+' <i class="fa fa-times-circle" onclick="delTdSpec(this,'+id+');"></i><input type="hidden" name="spec['+id+'][value][]" value="'+names+'">&nbsp;&nbsp;</span>');

                                layer.close(index);
                                //往数组里插入规格值
                                spec[id-1]['value'][length]=names;
                                //执行循环数组
                                specFor();

                            });
                            return false;

                        }

                        //删除规格值
                        function delTdSpec(obj,trid){
                            var a=$('.specKj tr');
                            var b=$('.trspec'+trid);
                            var c=a.index(b); //tr的索引

                            var d=b.find('span');
                            var e=$(obj).parent();
                            var f=d.index(e); //span的索引
                            //删除规格值
                            e.remove();
                            //删除数组里的规格值

                            spec[c]['value'].splice(f,1);
                            //执行循环数组
                            specFor();
                        }

                        //删除规格
                        function delSpec(id){
                            var a=$('.specKj tr');
                            var b=$('.trspec'+id);
                            var c=a.index(b);

                            //删除规格
                            b.remove();
                            //删除数组里的规格
                            spec.splice(c,1);
                            //执行循环数组
                            specFor();
                        }

                        //循环数组
                        function specFor(on){

                            var obj = $('.specvalue tbody');
                            obj.html('');

                            //循环出table头部
                            var thead='<tr>';
                            var rol=''; //主体总行数
                            for(var i=0;i < spec.length;i++){
                                if(spec[i]['value'].length != ''){
                                    rol+=spec[i]['value'].length+'*';
                                    thead+='<th>'+spec[i]['title']+'</th>';
                                }
                            }

                            //计算总行数
                            if(rol != ''){
                                thead+='<th>价格</th></tr>';
                                obj.prev().html(thead); //插入table头
                                rol=rol.substring(0,rol.length-1)
                                rolCount=eval(rol); //总行数

                                for(var i=1;i<=rolCount+1;i++){ //插入总行数
                                    obj.append('<tr class="priceTr"></tr>');
                                }



                                for(var i=0;i < spec.length;i++){ //插入规格值
                                    var length=spec[i]['value'].length;

                                    if(length != 0){
                                        for(var a=0;a < rolCount;a++){
                                            if(i == 0){
                                                is=rolCount/length;
                                                obj.find('tr').eq(a+1).append('<td class="td" data="'+parseInt(a/is)+'">'+spec[i]['value'][parseInt(a/is)]+'</td>');
                                            }else if(i == 1){
                                                if(length == 1){
                                                    obj.find('tr').eq(a+1).append('<td class="td" data="0">'+spec[i]['value'][0]+'</td>');
                                                }else{
                                                    obj.find('tr').eq(a+1).append('<td class="td" data="'+a%length+'">'+spec[i]['value'][a%length]+'</td>');
                                                }
                                            }else if(i == 2){
                                                if(length == 1){
                                                    obj.find('tr').eq(a+1).append('<td class="td" data="0">'+spec[i]['value'][0]+'</td>');
                                                }else{
                                                    is=parseInt(a/spec[1]['value'].length);
                                                    obj.find('tr').eq(a+1).append('<td class="td" data="'+parseInt(is%length)+'">'+spec[i]['value'][parseInt(is%length)]+'</td>');
                                                }
                                            }
                                        }
                                    }
                                }

                                for(var i=1;i<=rolCount;i++){ //插入规格值后面的td
                                    obj.find('tr').eq(i).append('<td><input type="text" class="allprice" name="" style="width:100px;"/></td>');
                                }

                                obj.next().html('<tr><td>批量设置：</td><td colspan="10"><a href="javascript:void(0);" onclick="allPrice();" class="btn btn-info btn-xs edit">价格</a><sapn style="color:red;margin-left:10px;float:right;">注意：请先把规则设置完了再设置价格库存等信息！</span></td></tr>');

//										if(on){ //说明是修改，把价格等填上
                                saveAll();
//										}
                            }

                            //设置价格库存等innput的name值
                            $('.priceTr').each(function(i){
                                var data='';
                                $(this).find('.td').each(function(){
                                    data += $(this).attr('data');
                                });

                                $(this).find('input').eq(0).attr('name',"specprice["+data+"][price]");
                                $(this).find('input').eq(1).attr('name',"specprice["+data+"][stock]");
                                $(this).find('input').eq(2).attr('name',"specprice["+data+"][design]");
                            })
                        }

                        //批量设置价格
                        function allPrice(){
                            layer.prompt({
                                title: '请输入价格：',
                                formType: 0 ,
                            }, function(name,index){

                                if(isNaN(name) || name<=0){
                                    layer.msg('请输入一个有效的价格！');
                                    return false;
                                }

                                $('.allprice').attr('value',name);
                                layer.close(index);

                            });
                            return false;
                        }

                        //计算
                        specFor(true);
                        //修改的时候把价格填上
                        function saveAll(){
                            var specPrice=new Array();
                            /*{notempty name="data.spec"}*/
                            /*{volist name="data.spec.price" id="vo"}*/
                            $('.allprice').eq({php}echo $i-1;{/php}).val('{$vo.price}');
                            /*{/volist}*/
                            /*{/notempty}*/
                        }
                    </script>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">是否推荐</label>
                        <div class="col-sm-8">
                            <div class="radio " style="display: inline-block;width: auto;">
                                <label class="" onclick="checkRadio(this)">
                                    <div class="iradio_square-green js-status {if condition='isset($data.is_recommend) && $data.is_recommend eq 0'}checked{/if}" style="position: relative;">
                                        <input type="radio" value="0" name="is_recommend" {if condition='isset($data.is_recommend) && $data.is_recommend eq 0'}checked{/if} style="position: absolute; opacity: 0;">
                                        <ins class="iCheck-helper" ></ins>
                                    </div>
                                    <i></i> 否
                                </label>
                            </div>
                            <div class="radio" style="display: inline-block;width: auto;margin-left: 15px;">
                                <label class="" onclick="checkRadio(this)">
                                    <div class="iradio_square-green js-status {if condition='isset($data.is_recommend) && $data.is_recommend eq 1'}checked{/if}" style="position: relative;">
                                        <input type="radio" value="1" name="is_recommend" {if condition='isset($data.is_recommend) && $data.is_recommend eq 1'}checked{/if} style="position: absolute; opacity: 0;">
                                        <ins class="iCheck-helper" ></ins>
                                    </div>
                                    <i></i> 是
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">是否销售</label>
                        <div class="col-sm-8">
                            <div class="radio " style="display: inline-block;width: auto;">
                                <label class="" onclick="checkSale(this)">
                                    <div class="iradio_square-green js-sale-status {if condition='isset($data.is_sale) && $data.is_sale eq 0'}checked{/if}" style="position: relative;">
                                        <input type="radio" value="0" name="is_sale" {if condition='isset($data.is_sale) && $data.is_sale eq 0'}checked{/if} style="position: absolute; opacity: 0;">
                                        <ins class="iCheck-helper" ></ins>
                                    </div>
                                    <i></i> 否
                                </label>
                            </div>
                            <div class="radio" style="display: inline-block;width: auto;margin-left: 15px;">
                                <label class="" onclick="checkSale(this)">
                                    <div class="iradio_square-green js-sale-status {if condition='isset($data.is_sale) && $data.is_sale eq 1'}checked{/if}" style="position: relative;">
                                        <input type="radio" value="1" name="is_sale" {if condition='isset($data.is_sale) && $data.is_sale eq 1'}checked{/if} style="position: absolute; opacity: 0;">
                                        <ins class="iCheck-helper" ></ins>
                                    </div>
                                    <i></i> 是
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">销量</label>
                        <div class="col-sm-8">
                            <input type="number" min="0" max="9999999" name="sale_num" value="{$data.sale_num|default=''}" placeholder="请输入商品销量" class="input-sm form-control">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">排序</label>
                        <div class="col-sm-8">
                            <input type="number" min="0" max="9999999" name="sort" placeholder="请输入商品排序值" value="{$data.sort|default=''}" class="input-sm form-control">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">详细介绍</label>
                        <div class="col-sm-8">
                            <textarea id="content" name="content" type="text/plain" style="width:100%;height:300px;">{notempty name="data.content"}{$data.content|htmlspecialchars_decode=###}{/notempty}</textarea>
                        </div>
                    </div>

                    <div class="hr-line-dashed"></div>
                    <div class="form-group">
                        <div class="col-sm-4 col-sm-offset-2">
                            <input class="btn btn-primary" type="submit" value="保存内容" />
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
    </form>
</div>
</body>
{/block}
{block name="js"}

<script type="text/javascript" charset="utf-8" src="__PUBLIC__/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="__PUBLIC__/ueditor/ueditor.all.min.js"> </script>
<script type="text/javascript" charset="utf-8" src="__PUBLIC__/ueditor/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript">
    var content = UE.getEditor('content');
</script>
<style>
    /*#edui1_iframeholder{max-height: 500px;}*/
</style>

<script type="text/javascript">
    $().ready(function() {
        $('#inp_1').change(function(event) {
            var self = this;
            var files = event.target.files || event.dataTransfer.files;
            var formData = new FormData();
            formData.append('imgFile', files[0]);
            var ajax = new XMLHttpRequest();
            ajax.open("POST", "{:url('index/Index/saveImg')}", true);
            ajax.send(formData);
            ajax.onreadystatechange = function() {
                if (ajax.readyState == 4) {
                    if (ajax.status >= 200 && ajax.status < 300 || ajax.status == 304) {
                        var data = JSON.parse(ajax.responseText);
                        if (data.status == 'y') {
                            $(self).prev().val(data.data.src);
                            $(self).prev().prev().attr('src', data.data.src);
                        } else {
                            layer.msg(data.info);
                        }
                    }
                }
            }
        });
    });

    function myAjaxSubmit() {
        if ($('form').hasClass('ed')) {
            return false;
        }
        var d = {};
        var t = $('form').serializeArray();
        $.each(t, function(i,n) {
            d[n.name] = n.value;
        });
        if (d.cate_id <= 0) {
            layer.msg('请选择商品分类');return false;
        }
        if (d.title == '') {
            layer.msg('请输入商品名称');return false;
        }
        if (d.img == '') {
            layer.msg('请上传商品图片');return false;
        }
        // if (d.price <= 0) {
        //     layer.msg('请输入商品单价');return false;
        // }
        if (d.content == '') {
            layer.msg('请输入商品详情');return false;
        }

        $('form').addClass('ed');
        $.post("{:url('save')}", $('form').serialize(), function(data){
            layer.msg(data.info);
            if (data.status == 'y') {
                setTimeout(function(){window.location.href = '{:url("index")}';},1500);
            } else {
                $('form').removeClass('ed');
            }
        }, 'json');
    }

    function checkRadio(self) {
        $('.js-status').removeClass('checked');
        $('.js-status input').prop('checked', false);
        $(self).children().addClass('checked').find('input').prop('checked', true);
    }

    function checkSale(self) {
        $('.js-sale-status').removeClass('checked');
        $('.js-sale-status input').prop('checked', false);
        $(self).children().addClass('checked').find('input').prop('checked', true);
    }


</script>
{/block}
